package com.maple.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.maple.constant.StatusConstant;
import com.maple.dto.DishDTO;
import com.maple.dto.DishPageQueryDTO;
import com.maple.entity.Dish;
import com.maple.entity.DishFlavor;
import com.maple.entity.Setmeal;
import com.maple.entity.SetmealDish;
import com.maple.enumeration.ExceptionEnum;
import com.maple.exception.BusinessException;
import com.maple.mapper.DishFlavorMapper;
import com.maple.mapper.DishMapper;
import com.maple.mapper.SetmealDishMapper;
import com.maple.mapper.SetmealMapper;
import com.maple.result.PageResult;
import com.maple.service.DishService;
import com.maple.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;


@Service
public class DishServiceImpl implements DishService {

    @Autowired
    DishMapper dishMapper;
    @Autowired
    DishFlavorMapper dishFlavorMapper;
    @Autowired
    SetmealMapper setmealMapper;
    @Autowired
    SetmealDishMapper setmealDishMapper;



    /**
     * 菜品分页查询
     * @param pageQueryDTO
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO pageQueryDTO) {
//        克隆对象
        Dish dish = new Dish();
        dish.setStatus(pageQueryDTO.getStatus());
        dish.setName(pageQueryDTO.getName());
        if (pageQueryDTO.getCategoryId() != null) {
            dish.setCategoryId(Long.valueOf(pageQueryDTO.getCategoryId()));
        }
//        BeanUtils.copyProperties(pageQueryDTO, dish);

//          开始数据库查询
        PageHelper.startPage(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
        Page<Dish> result = dishMapper.page(dish);

//        结果封装
        PageResult result1 = new PageResult();
        result1.setRecords(result.getResult());
        result1.setTotal(result.getTotal());

//        返回数据
        return result1;
    }

    /**
     * 根据菜品id查询相关数据
     * @param id
     * @return
     */
    @Override
    @Transactional
    public DishVO queryById(String id) {
//        调用数据库查询菜品
        Dish dish = new Dish();
        dish.setId(Long.valueOf(id));
        dish = dishMapper.query(dish);

//      查询菜品的口味
        List<DishFlavor> dishFlavor = dishFlavorMapper.queryByDishId(id);

//        封装口味数据
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavor);

//        返回结果
        return dishVO;
    }

    /**
     * 根据分类id查询菜品
     * @return
     */
    @Override
    public List<DishVO> queryByCategoryId(String categoryId) {
//      封装对象
        Dish dish = new Dish();
        dish.setCategoryId(Long.valueOf(categoryId));

//        查询数据库
        List<Dish> result = dishMapper.queryByCategoryId(categoryId);

//        封装对象
        List<DishVO> dishVO = result.stream().map(e -> {
            DishVO vo = new DishVO();
            BeanUtils.copyProperties(e, vo);
            return vo;
        }).toList();

//        返回结果
        return dishVO;

    }

    /**
     * 新增菜品
     * @param dishDTO
     */
    @Override
    @Transactional
    public void save(DishDTO dishDTO) {
//        克隆菜品对象
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

//        判断菜品在数据库中是否重复
        Dish query = dishMapper.query(dish);
        if(query != null){
            throw new BusinessException(ExceptionEnum.ALREADY_EXISTS);
        }

//        新增数据库菜品数据
        if(dish.getStatus() == null){
//            设置初始状态为停售
            dish.setStatus(StatusConstant.DISABLE);
        }
        dishMapper.save(dish);

//          生成口味对象
        List<DishFlavor> flavors = dishDTO.getFlavors();

//        补全属性,新增数据库口味数据
        if (flavors != null && !flavors.isEmpty()) {
            flavors.forEach(flavor -> flavor.setDishId(dish.getId()));
            dishFlavorMapper.save(flavors);
        }

    }

    /**
     * 更新菜品售卖状态
     * @param status
     * @param id
     */
    @Override
    public void changeStatus(Integer status, String id) {
//        封装对象
        Dish dish = Dish.builder()
                .status(status)
                .id(Long.valueOf(id))
                .build();

//        数据库更新
        dishMapper.update(dish);

//        如果是停售，还需要停售相关套餐
        if(status.equals(StatusConstant.DISABLE)){
//            获得套餐id
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(Long.valueOf(id));
            List<Long> setmealIds  = setmealDishMapper.getSetmealIdsByDishIds(dishIds);

//            封装套餐对象
            for(Long setmealId : setmealIds){
                Setmeal setmeal = Setmeal.builder()
                        .status(status)
                        .id(setmealId)
                        .build();
                setmealMapper.update(setmeal);
            }

        }


    }

    /**
     * 菜品修改
     * @param dishDTO
     */
    @Override
    @Transactional
    public void update(DishDTO dishDTO) {
//        克隆菜品对象
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

//        克隆口味对象
        List<DishFlavor> flavors = dishDTO.getFlavors();

//        数据库菜品修改
        dishMapper.update(dish);

//        数据库口味删除
        List<Long> list = new ArrayList<>();
        list.add(dish.getId());
        dishFlavorMapper.deleteByIds(list);

//        补全属性,新增数据库口味数据
        if (flavors != null && !flavors.isEmpty()) {
            flavors.forEach(flavor -> flavor.setDishId(dish.getId()));
            dishFlavorMapper.save(flavors);
        }

    }

    /**
     * 根据id批量删除
     * @param ids
     */
    @Override
    @Transactional
    public void deleteById(List<Long> ids) {
//        判断菜品下是否存在套餐
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if(setmealIds != null && !setmealIds.isEmpty()){
            throw new BusinessException(ExceptionEnum.DISH_BE_RELATED_BY_SETMEAL);
        }

//        判断删除的菜品中是否存在停售的菜品
        for(Long id : ids){
            Dish dish = Dish.builder().id(id).build();
            Dish query = dishMapper.query(dish);
            if(Objects.equals(query.getStatus(), StatusConstant.DISABLE)){
                throw new BusinessException(ExceptionEnum.DISH_ON_SALE);
            }
        }

//        根据id删除菜品
        dishMapper.deleteByIds(ids);

//        删除口味
        dishFlavorMapper.deleteByIds(ids);
    }

    /**
     * 根据分类id查询相关菜品
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> list(String categoryId) {
//        调用数据库进行查询起售中的菜品
        Dish dish = Dish.builder()
                .status(StatusConstant.ENABLE)
                .categoryId(Long.valueOf(categoryId))
                .build();
        List<Dish> list = dishMapper.page(dish);

//        获得菜品id，并进行口味查询
        List<DishVO> dishVOList = new ArrayList<>();
        for(Dish e : list){
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(e, dishVO);
            Long id = e.getId();
            dishVO.setFlavors(dishFlavorMapper.queryByDishId(String.valueOf(id)));
            dishVOList.add(dishVO);
        }

//        返回值
        return dishVOList;
    }


}
